package com.handwriting.backend.api;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.client.MultipartBodyBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.net.URI;

@Component
public class PythonAPI {

    @Value("${python.api.server.url}")
    private String url;
    private final WebClient client;

    public PythonAPI() {
        this.client = WebClient.create(url);
    }

    public String post(String jsonStr, URI uri) {
        Mono<String> mono = client.post()
                .uri(uri)
                .contentType(MediaType.APPLICATION_JSON)
                .body(BodyInserters.fromValue(jsonStr))
                .retrieve()
                .bodyToMono(String.class);
        return mono.block();
    }

    public String get(URI uri) {
        Mono<String> mono = client.get()
                .uri(uri)
                .retrieve()
                .bodyToMono(String.class);
        return mono.block();
    }

    public String postForm(MultipartBodyBuilder builder, URI uri) {
        Mono<String> mono = client.post()
                .uri(uri)
                .contentType(MediaType.MULTIPART_FORM_DATA)
                .body(BodyInserters.fromMultipartData(builder.build()))
                .retrieve()
                .bodyToMono(String.class);
        return mono.block();
    }
}
